package fudan.se.project.service.infrastructure.entity.message;


import fudan.se.project.domain.User;
import fudan.se.project.domain.conference.Conference;
import fudan.se.project.domain.message.Invitation;
import fudan.se.project.repository.entity.message.InvitationRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class InvitationService {

    private final InvitationRepository invitationRepository;

    public InvitationService(InvitationRepository invitationRepository) {
        this.invitationRepository = invitationRepository;
    }


    public Invitation save(Invitation invitation) {
        return invitationRepository.save(invitation);
    }

    public Invitation createInvitation(User sender, User receiver, Conference conference) {
        return this.save(new Invitation(sender, receiver, conference));
    }

    public Invitation changeInvitationState(Invitation invitation, Invitation.State state) {
        invitation.setState(state);
        return this.save(invitation);
    }


    //<editor-fold desc="entity query method">
    private static final int SIZE = 3;

    private static final Sort sort = Sort.by(Sort.Direction.DESC, "dateCreated");

    public Page<Invitation> getInvitationsBySender(User sender, int page) {
        return invitationRepository.
                findBySender(sender,
                        PageRequest.of(page - 1, SIZE, sort)
                );
    }

    public Page<Invitation> getInvitationsByReceiver(User receiver, int page) {
        return invitationRepository.
                findByReceiver(receiver,
                        PageRequest.of(page - 1, SIZE, sort)
                );
    }

    public Invitation findById(long id) {
        return invitationRepository.findById(id);
    }

    public Invitation findBySenderAndReceiverWithStateInConference(
            User sender, User receiver,
            Conference conference, Invitation.State state
    ) {
        return invitationRepository.findBySenderAndReceiverWithStateInConference(
                sender, receiver, conference, state
        );
    }
    //</editor-fold>
}
